package com.cugbmao.lucene.util;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class TestUtil {
	public static int hitCount( final IndexSearcher searcher, final Query query ) throws IOException {
		return searcher.search( query, 1 ).totalHits;
	}

	public static void rmDir( File dir ) throws IOException {
		if ( dir.exists() ) {
			File[] files = dir.listFiles();
			for ( int i = 0; i < files.length; i++ ) {
				if ( !files[i].delete() ) {
					throw new IOException( "could not delete " + files[i] );
				}
			}
			dir.delete();
		}
	}

	public static Directory getBookIndexDirectory() throws IOException {
		System.out.println( System.getProperty( "index.dir" ) );
		return FSDirectory.open( new File( System.getProperty( "index.dir" ) ) );
	}

	/**
	 * @param searcher
	 * @param docs
	 * @param string
	 * @return
	 */
	public static boolean hitsIncludeTitle( IndexSearcher searcher, TopDocs docs, String title ) throws IOException {
		for ( ScoreDoc doc : docs.scoreDocs ) {
			Document d = searcher.doc( doc.doc );
			if ( title.equals( d.get( "title" ) ) ) {
				return true;
			}
		}
		System.out.println( "title '" + title + "' not found" );
		return false;
	}
}
